package com.gateway.filter;

import com.entity.MyToken;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.Cookies;

import java.net.URI;
import java.util.UUID;

/**
 * 登录拦截器
 */
@Component
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        URI uri = exchange.getRequest().getURI();
        String path = uri.getPath();
        String userName = exchange.getRequest().getQueryParams().get("userName").get(0);
        String reqPwd = exchange.getRequest().getQueryParams().get("pwd").get(0);

        if( ! MyToken.TOKEN_MAP.containsKey(userName)){
            //拒绝访问
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "请进行登录";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        if(path.indexOf("login")>-1){
//            验证密码

            String pwd = MyToken.USER_MAP.get(userName).toString();
            if(reqPwd.equals(pwd)){
                UUID uuid = UUID.randomUUID();
                MyToken.TOKEN_MAP.put(userName, uuid.toString());
                ServerHttpResponse response = exchange.getResponse();
                ResponseCookie build = ResponseCookie.from(userName, uuid.toString()).build();
                response.addCookie(build);
            }
        }

        return chain.filter(exchange);
    }
}
